// reder函数， 将一个bnode函数绚烂到dom节点上
import { render, h, reactive } from 'vue'
import type { createAlertProps, AlertContext } from './type'
import AlertConstructor from './index.vue'
// 创建一个数组 = 存放组件的实例
const instances: AlertContext[] = reactive([])
let seed = 1
export const createAlert = (props: createAlertProps) => {
  const id = `alert_${seed++}`
  // 移除节点方法
  const destroy = () => {
    const idx = instances.findIndex(instance => instance.id == id)
    if (idx === -1) return
    instances.splice(idx, 1)
    render(null, container)
  }
  // 移除
  const newProps = {
    ...props,
    onDestroy: destroy,
    id
  }
  // 创建dom元素
  const container = document.createElement('div')
  // 创建虚拟dom
  const vnode = h(AlertConstructor, newProps)
  // 渲染dom
  render(vnode, container)

  // 添加到页面中
  document.body.appendChild(container.firstElementChild!)
  const vm = vnode.component!
  // 创建组件实例
  const instance = {
    id,
    vnode,
    props: newProps,
    vm
  }
  instances.push(instance)
  return instance
}

// 可以获取最后一个实例
export const getLastInstance = () => {
  return instances[instances.length]
}

// 获取上一个实例最下面的坐标位置
export const getLastBottomOffset = (id: string) => {
  const idx = instances.findIndex(instance => instance.id == id)
  console.log(idx);

  if (idx <= 0) {
    return 0
  } else {
    const prev = instances[idx - 1]
    console.log(prev.vm.exposed!.bottomOffset.value);

    return prev.vm.exposed!.bottomOffset.value
  }
}
